package org.abratuhi.kvngroupware.pubsub;

import java.util.HashMap;

public class Subscription<T> {
	
	String subscriberId;
	HashMap<String, Range<T>> ranges = new HashMap<String, Range<T>>();
	
	public Subscription(String subId){
		this.subscriberId = subId;
	}
	
	public void addAttribute(String attributeId, Range<T> range){
		ranges.put(attributeId, range);
	}
	
	public void removeAttribute(String attributeId){
		ranges.remove(attributeId);
	}
	
	public void updateAttribute(String attributeId, Range<T> range){
		if(ranges.containsKey(attributeId)) ranges.put(attributeId, range);
	}
	
	public boolean containsAttribute(String attributeId){
		return ranges.containsKey(attributeId);
	}
	
	public Range<T> getRange(String attributeId){
		return ranges.get(attributeId);
	}
	
	public String getSubscriberId(){
		return this.subscriberId;
	}
	
	public String[] getAttributeIds(){
		return ranges.keySet().toArray(new String[ranges.keySet().size()]);
	}
	
	public boolean matches(Publication<T> pub, String attributeId){
		Value<T> value = pub.getValue(attributeId);
		Range<T> range = getRange(attributeId);
		return (range.getLowerBound().compareTo(value) < 0 
				&& value.compareTo(range.getUpperBound()) < 0);
	}
	
	public boolean matches(Publication<T> pub){
		String[] attributeIds = pub.getAttributeIds();
		for(int i=0; i<attributeIds.length; i++)
			if(containsAttribute(attributeIds[i]) 
					&& !matches(pub, attributeIds[i]))
				return false;
		return true;
	}
	
	public boolean intersects(String attributeId, Range<T> arange){
		return getRange(attributeId).intersects(arange);
	}
	
	public String toString(){
		String result = new String();
		String[] attributes = getAttributeIds();
		for(int i=0; i<attributes.length; i++){
			String attribute = attributes[i];
			Range<T> range = ranges.get(attribute);
			result += range.getLowerBound().toString() + " <= " + attribute + " <= " + range.getUpperBound().toString() + ", ";
		}
		//result += "\n";
		return result;
	}

}
